// WebSocket.js
class WebSocketService {
    constructor(url) {
        this.socket = null;
        this.url = url;
        this.callbacks = {};
    }
 
    // 连接WebSocket
    connect() {
        this.socket = new WebSocket(this.url);
 
        this.socket.onopen = () => {
            console.log('WebSocket连接已建立');
            if (this.callbacks['open']) {
                this.callbacks['open']();
            }
        };
 
        this.socket.onmessage = (event) => {
            const data = JSON.parse(event.data);
            console.log('收到消息:', data);
            if (this.callbacks['message']) {
                this.callbacks['message'](data);
            }
        };
 
        this.socket.onclose = () => {
            console.log('WebSocket连接已关闭');
            if (this.callbacks['close']) {
                this.callbacks['close']();
            }
        };
 
        this.socket.onerror = (error) => {
            console.error('WebSocket发生错误:', error);
            if (this.callbacks['error']) {
                this.callbacks['error'](error);
            }
        };
    }
 
    // 发送消息
    send(message) {
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            this.socket.send(JSON.stringify(message));
        } else {
            console.error('WebSocket未连接，无法发送消息');
        }
    }
 
    // 注册回调函数
    on(event, callback) {
        this.callbacks[event] = callback;
    }
 
    // 关闭WebSocket连接
    close() {
        if (this.socket) {
            this.socket.close();
        }
    }
}
 
export default WebSocketService;